<?php
$curl=curl_init();
curl_setopt_array($curl, array(
	CURLOPT_RETURNTRANSFER =>1,
	CURLOPT_URL => 'http://74.3.165.182/jlogin/init/ghostec',
	CURLOPT_USERAGENT => 'Chess Time 3.7 (IPhone; Iphone OS 7.0.2;en_US)'
));
$resp=curl_exec($curl);
print $resp."\n";
$token=substr($resp,13,61);


curl_close($curl);

# Prepare for login 

$poststring = '{"code":"'.$token.'","password":"somepassword"}';
print $poststring."\n";
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $poststring
    )
);

# Create the context
$context = stream_context_create($opts);

# Get the response (you can use this for GET)
$result = file_get_contents('http://74.3.165.182/jlogin/enter', false, $context);


print "login should be ok ".$result."\n";

# Token verification
 
$newurl='http://74.3.165.182/juser/devitoken?tkn='.$token;
$opts['http']['content']='{"token":"'.$token.'bed"}';
$context = stream_context_create($opts);
$result = file_get_contents($newurl, false, $context);
print "token verified ".$result."\n";

# Look for the active games

$newurl='http://74.3.165.182/jgame/active?tkn='.$token;
$result = file_get_contents($newurl);
print "Active Games\n";
print $result."\n";

# Decoding Json response
$jresult= json_decode($result,true);
//var_dump($jresult);

$id=$jresult['result']['games'][0]['id'];
print "id of a first game =".$id."\n";
print "\n";

$games=$jresult['result']['games'];
$count=count($games);
print "i have found ".$count." games";
print "\n\n\n";

$i=0;
while ($i<=$count-1) {
	
	if ($games[$i]['gameState']!='COMPLETE') {
		print "Gamesstate =".$games[$i]['gameState']."  ";
		print "id".$i."= ".$games[$i]['id']."\n";
		
		}
	$i++;

	}



$newurl='http://74.3.165.182/jgame/game/'.$id.'?tkn='.$token;
$newresult = file_get_contents($newurl);
$newjresult= json_decode($newresult,true);
//var_dump($newjresult);
$gamedata=$newjresult['result']['gameData'];
$oldmoves1=strpos($gamedata,"Moves:");
$oldmoves2=strpos($gamedata,"CastleSquares");
$oldmoves=substr($gamedata,$oldmoves1+6,$oldmoves2-$oldmoves1-7);
print $gamedata."\n";
print "position=".$oldmoves1."\n";
print "position=".$oldmoves2."\n";
print "string=".$oldmoves."\n";

?>

